package com.kaizeli.website.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kaizeli.website.response.Result;
import com.kaizeli.website.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 管理员权限拦截器
 * 用于拦截需要管理员权限的接口
 */
@Slf4j
@Component
public class AdminAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 处理OPTIONS预检请求
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        String token = null;
        
        // 1. 从Authorization头获取Token
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            token = authHeader.substring(7);
        }
        
        // 2. 如果Header中没有，尝试从请求参数获取
        if (token == null) {
            token = request.getParameter("token");
        }

        // 3. 验证Token是否存在（暂时设为非必填）
        if (token == null || token.trim().isEmpty()) {
            log.info("请求未携带Token，允许通过，请求路径：{}", request.getRequestURI());
            return true;
        }

        try {
            // 4. 从token获取用户名
            String username = JwtUtil.getUsernameFromToken(token);
            
            if (username == null || username.trim().isEmpty()) {
                log.warn("Token无效，无法获取用户名");
                sendErrorResponse(response, 401, "Token无效，请重新登录");
                return false;
            }

            // 5. 从数据库查询用户信息
            String sql = 
                "SELECT id, username, administrator, is_token_valid, token_expires_at " +
                "FROM users " +
                "WHERE username = ?";
            
            Map<String, Object> user;
            try {
                user = jdbcTemplate.queryForMap(sql, username);
            } catch (Exception e) {
                log.warn("用户不存在：{}", username);
                sendErrorResponse(response, 401, "用户不存在");
                return false;
            }

            // 6. 检查是否为管理员或总管理员（级别>=1）
            Object adminObj = user.get("administrator");
            int userLevel;
            if (adminObj instanceof Number) {
                userLevel = ((Number) adminObj).intValue();
            } else {
                userLevel = 0;
            }

            // 只有管理员(1)和总管理员(2)可以访问，子管理员(0)不可以
            if (userLevel < 1) {
                log.warn("用户 {} 权限不足（级别：{}），尝试访问：{}", username, userLevel, request.getRequestURI());
                sendErrorResponse(response, 403, "权限不足：只有管理员及以上级别可以访问此功能");
                return false;
            }

            // 7. 将用户信息存储到请求属性中，供Controller使用
            request.setAttribute("userId", user.get("id"));
            request.setAttribute("username", username);
            request.setAttribute("administrator", userLevel >= 1);
            request.setAttribute("userLevel", userLevel);

            log.debug("管理员权限验证成功，用户：{}，级别：{}", username, userLevel);
            return true;

        } catch (Exception e) {
            log.error("管理员权限验证失败：{}", e.getMessage(), e);
            sendErrorResponse(response, 401, "权限验证失败，请重新登录");
            return false;
        }
    }

    /**
     * 发送错误响应
     */
    private void sendErrorResponse(HttpServletResponse response, int code, String message) throws Exception {
        response.setStatus(code == 401 ? HttpServletResponse.SC_UNAUTHORIZED : HttpServletResponse.SC_FORBIDDEN);
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        
        Result<Object> result = Result.error(code, message);
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonResponse = objectMapper.writeValueAsString(result);
        
        response.getWriter().write(jsonResponse);
        response.getWriter().flush();
    }
}

